import React from 'react'
import {isArray, isEmpty, isFunction} from 'lodash-es'
import PropTypes from "prop-types";
import {updateTreeData} from './helper'
import TreeBase from "./TreeBase";
/**
 * 纯展示树组件
 * （1）数据源：props.compData ，或从接口获取数据（props.fetchTree）。当传 props.fetchTree 方法，props.compData 会被忽略
 * （2）操作：搜索节点，加载子节点；
 */
export default class TreeComp extends TreeBase {

    static propTypes = {
        ...TreeBase.propTypes,
        fetchTree: PropTypes.func,
        loading: PropTypes.bool
    };

    componentDidMount() {
        super.componentDidMount();
        this.fetchTree();
    }

    /**
     * 异步请求树列表数据
     */
    fetchTree() {
        const {fetchTree} = this.props;
        if (isFunction(fetchTree)) {
            let reFunc = fetchTree({search: this.state.searchValue});

            if (reFunc instanceof Promise) {
                reFunc.then(treeData => {
                    this.setState({list: treeData || []});
                });
            }
        }
    }

    /**
     * 搜索框输入后，再执行筛选逻辑之前，会执行此回调。
     * @param value {string} 搜索框的值
     * @return {boolean} 返回 false 时，不再执行默认筛选逻辑。返回 true 时，执行默认的筛选逻辑。
     */
    beforeSearch(value) {
        let goOn = true;
        const {fetchTree} = this.props;

        if (isFunction(fetchTree)) {
            goOn = false;

            this.setState({searchValue: value, autoExpandParent: true}, () => {
                this.fetchTree();
            });
        }
        return goOn;
    }

    /**
     * 异步加载子节点。Tree 组件的 loadData 属性.
     * @param node
     * @return {Promise<unknown>}
     */
    hdlLoadData(node) {
        const {key, children} = node;
        // console.log('hdlLoadData');

        return new Promise(resolve => {

            if (!isEmpty(children)) { // 有子节点
                resolve();
                return;
            }

            // 通过异步请求，获取子节点
            const {fetchTree} = this.props;

            if (isFunction(fetchTree)) {
                let reFunc = fetchTree({search: this.state.searchValue, node});

                if (reFunc instanceof Promise) {
                    reFunc.then(rspData => {

                        if (isArray(rspData)) {
                            let newState = {};
                            // 将子节点更新到当前节点
                            newState.list = updateTreeData(this.state.list, key, rspData);

                            const {expandedKeys} = this.state;
                            if (expandedKeys.indexOf(key) === -1) {
                                let newExpandedKeys = [...expandedKeys];
                                newExpandedKeys.push(key);
                                newState.expandedKeys = newExpandedKeys;
                            }
                            this.setState(newState);
                        } else {
                            // 加载数据失败，从 expandedKeys 中移除这个 key
                            setTimeout(() => {
                                const {expandedKeys} = this.state;
                                let newExpandedKeys = [...expandedKeys];
                                let curInd = newExpandedKeys.indexOf(key);

                                if (-1 !== curInd) {
                                    delete newExpandedKeys[curInd];
                                }
                                this.setState({expandedKeys: newExpandedKeys});

                            }, 0);
                            // message.error('加载失败，请重新点击!')
                        }
                        resolve();
                        return rspData;
                    });
                    return;
                }
            }
            resolve();

        });
    }

    /**
     * 设置 Tree 组件的属性，每次 render 都会执行此方法
     * @return {{}} 可设置的属性，参照 antd 的 Tree 组件
     */
    setTreePropsInRender() {
        const {fetchTree} = this.props;
        const moreProps = {};

        if (isFunction(fetchTree)) {
            moreProps.loadData = this.hdlLoadData.bind(this);
            moreProps.loadedKeys = [];
        }
        return moreProps;
    }

}